package com.sh.museum.ui;

import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.marshalchen.common.uimodule.androidanimations.Techniques;
import com.marshalchen.common.uimodule.androidanimations.YoYo;
import com.marshalchen.common.uimodule.nineoldandroids.animation.Animator;
import com.sh.museum.R;
import com.sh.museum.adapter.DigitalAdapter;
import com.sh.museum.base.BaseActivity;
import com.sh.museum.common.Constants;
import com.sh.museum.db.ResourceDb;
import com.sh.museum.entities.PlayInfo;
import com.sh.museum.utils.FileUtils;
import com.sh.museum.utils.PlayUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by baishiwei on 2015/1/23.
 */
@ContentView(R.layout.digital)
public class Diaital extends BaseActivity {
    @ViewInject(R.id.top_back_btn)
    ImageButton back;
    @ViewInject(R.id.top_title)
    TextView title;
    @ViewInject(R.id.list)
    private ListView list;
    @ViewInject(R.id.search)
    private ImageButton search;
    private Cursor cursor;
    private ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
    private DigitalAdapter adapter;
    @ViewInject(R.id.input)
    private EditText input;
    @ViewInject(R.id.key_board)
    private LinearLayout keyBoard;
    @ViewInject(R.id.btn_num_0)
    private ImageButton key_board_0;
    @ViewInject(R.id.btn_num_1)
    private ImageButton key_board_1;
    @ViewInject(R.id.btn_num_2)
    private ImageButton key_board_2;
    @ViewInject(R.id.btn_num_3)
    private ImageButton key_board_3;
    @ViewInject(R.id.btn_num_4)
    private ImageButton key_board_4;
    @ViewInject(R.id.btn_num_5)
    private ImageButton key_board_5;
    @ViewInject(R.id.btn_num_6)
    private ImageButton key_board_6;
    @ViewInject(R.id.btn_num_7)
    private ImageButton key_board_7;
    @ViewInject(R.id.btn_num_8)
    private ImageButton key_board_8;
    @ViewInject(R.id.btn_num_9)
    private ImageButton key_board_9;
    @ViewInject(R.id.btn_num_delete)
    private ImageButton key_board_delete;
    @ViewInject(R.id.btn_num_gone)
    private ImageButton key_board_gone;
    private boolean isShowKeyBoard;
    private String currentDigital = "";
    private PlayInfo info;
    private String language = Constants.LANGUAGE;
    private boolean searchFlag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        title.setText(R.string.digital);
        adapter = new DigitalAdapter(this, data);
        list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                info = PlayUtils.setPlayInfo(data.get(position));
                mHandler.sendEmptyMessage(0);
            }
        });
        isShowKeyBoard = true;
        keyBoard.setVisibility(View.VISIBLE);

    }

    @Override
    protected void onResume() {
        super.onResume();
        list.setVisibility(View.GONE);

    }

    private void imageItem(Map<String, Object> item, String mCurID) {
        String temp_path = Constants.BASEPATH + language + "/" + mCurID + "/" + mCurID + "_icon.png";
        File imageFile = new File(temp_path);
        if (imageFile.exists()) {
            item.put("Image", BitmapFactory.decodeFile(temp_path));
        } else {
            item.put("Image", BitmapFactory.decodeResource(getResources(), R.drawable.default_image));
        }
    }

    @OnClick(R.id.top_back_btn)
    public void back(View view) {
        defaultFinish();
    }

    private void inputNum(int num) {
        if (currentDigital.length() < 8) {
            input.setText(currentDigital += num);
            input.setSelection(currentDigital.length());
        } else {
            currentDigital = "";
            input.setText(R.string.max_support_text);
        }
    }

    @OnClick(R.id.btn_num_0)
    public void keyBoard0(View view) {
        inputNum(0);
    }

    @OnClick(R.id.btn_num_1)
    public void keyBoard1(View view) {
        inputNum(1);
    }

    @OnClick(R.id.btn_num_2)
    public void keyBoard2(View view) {
        inputNum(2);
    }

    @OnClick(R.id.btn_num_3)
    public void keyBoard3(View view) {
        inputNum(3);
    }

    @OnClick(R.id.btn_num_4)
    public void keyBoard4(View view) {
        inputNum(4);
    }

    @OnClick(R.id.btn_num_5)
    public void keyBoard5(View view) {
        inputNum(5);
    }

    @OnClick(R.id.btn_num_6)
    public void keyBoard6(View view) {
        inputNum(6);
    }

    @OnClick(R.id.btn_num_7)
    public void keyBoard7(View view) {
        inputNum(7);
    }

    @OnClick(R.id.btn_num_8)
    public void keyBoard8(View view) {
        inputNum(8);
    }

    @OnClick(R.id.btn_num_9)
    public void keyBoard9(View view) {
        inputNum(9);
    }

    @OnClick(R.id.btn_num_delete)
    public void delete(View view) {
        if (currentDigital.length() > 1) {
            currentDigital = currentDigital.substring(0,
                    currentDigital.length() - 1);
            input.setText(currentDigital);
            input.setSelection(currentDigital.length());
        } else {
            currentDigital = "";
            input.setText("");
        }
    }

    @OnClick(R.id.btn_num_gone)
    public void gone(View view) {
        hideKeyBoard();
        isShowKeyBoard = false;
    }

    private void hideKeyBoard() {
        YoYo.with(Techniques.TakingOff).duration(800).interpolate(new AccelerateDecelerateInterpolator())
                .withListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        keyBoard.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {
                    }

                    @Override
                    public void onAnimationRepeat(Animator animation) {
                    }
                })
                .playOn(keyBoard);
    }


    @OnClick(R.id.input)
    public void input(View view) {
        input.setCursorVisible(true);
        hideKeyboard(input);
        if (isShowKeyBoard) {
            isShowKeyBoard = false;
            hideKeyBoard();
        } else {
            isShowKeyBoard = true;
            keyBoard.setVisibility(View.VISIBLE);
            YoYo.with(Techniques.Landing).duration(800).playOn(keyBoard);
        }
        YoYo.with(Techniques.Pulse).duration(1500).playOn(view);
    }

    @OnClick(R.id.search)
    public void search(View view) {
        if (!TextUtils.isEmpty(currentDigital)) {
            String temp_num = String.format("%1$04d", Integer.parseInt(currentDigital));
            //currentDigital = "";
            cursor = ResourceDb.get_instance().PlayByFileNum(language, temp_num);
            if (cursor != null) {
                cursor.moveToNext();
                info = PlayUtils.setPlayInfo(cursor);
                if (!FileUtils.isFileExist(cursor.getString(2), cursor.getString(1), cursor.getString(3))) {
                    showShortToast(R.string.please_download_resource);
                    openActivity(Settings.class);
                } else {
                    if (data != null) {
                        data.clear();
                    }
                    Map<String, Object> item = new HashMap<String, Object>();
                    imageItem(item, cursor.getString(1));
                    item.put("title", cursor.getString(4));
                    item.put("Num", String.format("%1$04d", Integer.parseInt(cursor.getString(1))));
                    item.put("Path", cursor.getString(2));
                    item.put("Type", cursor.getString(3));
                    data.add(item);
                    adapter.notifyDataSetChanged();
                    list.setVisibility(View.VISIBLE);
                    searchFlag = true;
                }
            } else {
                //input.setText(R.string.invalid_number);
                Toast.makeText(Diaital.this, getResources().getString(R.string.invalid_number), Toast.LENGTH_SHORT).show();
                list.setVisibility(View.INVISIBLE);
            }
        } else {
            input.setText("");
        }
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("PlayInfo", info);
                    openActivity(AudioPlayer.class, bundle);
                    currentDigital = "";
                    input.setText("");
                    searchFlag = false;
                    break;
            }
        }
    };
}
